﻿using System;
using System.Timers;
using RssDataModel.Properties;
using System.Collections.Generic;

namespace RssDataModel
{
    class ArticleDownloader
    {
        const int ARTICLE_MAX_AGE=48;//in hours
        private Timer testTimer;
        private DataClasses datamodel;

        //public DataHandlerTimer()
        //    : this(new DataHandler())
        //{
        //}

        public ArticleDownloader(DataClasses datamodel)
        {
            this.datamodel = datamodel;
            updateArticlesFromFeeds();
            //todo: get timer settings from config file
            testTimer = new System.Timers.Timer(Settings.Default.updateTimer*60*1000); //  5 minute = 5*60*(1000 miliseconds)
            testTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
            
            testTimer.Enabled = true;
            testTimer.AutoReset = true;
        }

        private void OnTimerElapsed(object source, ElapsedEventArgs e)
        {
            updateArticlesFromFeeds();

            //Todo: send read notification to log
            Console.WriteLine("timer event activated !");
        }

        /// <summary>
        /// reads articles from all feeds loads them in DB 
        /// deletes articles older than required, which have no user references to
        /// </summary>
        internal void updateArticlesFromFeeds()
        {
            IEnumerable<article> newArticles = datamodel.getArticlesFromRSSFeeds();
            datamodel.addArticlesToDB(newArticles);
            datamodel.deleteArticlesOlderThan(ARTICLE_MAX_AGE);
        }
    }
}
